package com.example.nftapp.adapter;

import android.annotation.SuppressLint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.nftapp.R;
import com.example.nftapp.beans.BannerHttp;

import java.util.List;

public class BannerAdapterHttp extends RecyclerView.Adapter<BannerAdapterHttp.BannerViewHolder> {

    private final List<BannerHttp> bannerDatas;
    private final OnBannerItemClickListener onBannerItemClickListener;

    public interface OnBannerItemClickListener {
        void onClick(int position);
    }

    /**
     * 第3步 通过构造函数，传入图片数据资源
     */
    public BannerAdapterHttp(List<BannerHttp> bannerDatas, OnBannerItemClickListener onBannerItemClickListener) {
        this.bannerDatas = bannerDatas;
        this.onBannerItemClickListener = onBannerItemClickListener;
    }

    /**
     * 将轮播图的Item的布局文件转换成View
     *
     * @param parent   The ViewGroup into which the new View will be added after it is bound to
     *                 an adapter position.
     * @param viewType The view type of the new View.
     * @return
     */
    @NonNull
    @Override
    public BannerAdapterHttp.BannerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_item_vp_banner, parent, false);
        // 将布局文件解析得到的View，通过BannerViewHolder包装起来，实现复用
        return new BannerViewHolder(view);
    }

    /**
     * 将数据与View绑定
     *
     * @param holder   The ViewHolder which should be updated to represent the contents of the
     *                 item at the given position in the data set.
     * @param position The position of the item within the adapter's data set.
     */
    @Override
    public void onBindViewHolder(@NonNull BannerAdapterHttp.BannerViewHolder holder, @SuppressLint("RecyclerView") int position) {
        BannerHttp bannerHttp = bannerDatas.get(position);
        Glide.with(holder.imageView).load(bannerHttp.getImagePath()).into(holder.imageView);
        holder.imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBannerItemClickListener.onClick(position);
            }
        });
    }

    /**
     * 返回轮播图的数量
     *
     * @return
     */
    @Override
    public int getItemCount() {
        return bannerDatas.size();
    }

    /**
     * 通过ViewHolder实现View的复用
     */
    public static class BannerViewHolder extends RecyclerView.ViewHolder {

        ImageView imageView;

        public BannerViewHolder(@NonNull View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.ivBannerPic);
        }
    }
}